package com.keehin.barcode;

import javax.swing.SwingUtilities;
import java.awt.BorderLayout;

import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFrame;

import com.keehin.DBTable;
import com.keehin.DBTableModel;
import com.keehin.Database;
import com.keehin.MyRenderer;
import com.keehin.ReportDriver;

import java.awt.Dimension;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Locale;

import javax.swing.JScrollPane;
import java.awt.Rectangle;
import javax.swing.JTable;

import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.Font;
import java.awt.event.KeyEvent;

public class StockBarcode extends JFrame {

	private static final MyRenderer MY_RENDERER = new MyRenderer();
	private static final Font FONT1 = new Font("Tahoma", Font.PLAIN, 18);
	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private Database db; // @jve:decl-index=0:
	private JScrollPane jScrollPane = null;
	private DBTable jTable = null;
	private JPanel jPanel = null;
	private DBTableModel tm;
	private JTextField code = null;
	private JTextField descript = null;
	private JLabel jLabel2 = null;
	private JLabel jLabel3 = null;
	private JComboBox rowcount = null;

	private PreparedStatement pstmt;

	private TableRowSorter<TableModel> sorter;
	private JLabel count = null;

	private HashMap<String, Object> params = new HashMap<String, Object>();

	/**
	 * This method initializes jScrollPane
	 * 
	 * @return javax.swing.JScrollPane
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setViewportView(getJTable());
		}
		return jScrollPane;
	}

	/**
	 * This method initializes jTable
	 * 
	 * @return javax.swing.JTable
	 */
	private JTable getJTable() {
		if (jTable == null) {
			jTable = new DBTable();
			jTable.setFont(FONT1);
			jTable.setToolTipText("ดับเบิ้ลคลิกซ์หรือกดปุ่ม [space bar] เพื่อพิมพ์บาร์โค้ด");
			jTable.addKeyListener(new java.awt.event.KeyAdapter() {
				public void keyPressed(java.awt.event.KeyEvent e) {
					if (e.getKeyCode() == KeyEvent.VK_SPACE) {
						showReport();
					}
				}
			});

			jTable.addMouseListener(new java.awt.event.MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					if (e.getClickCount() == 2) {
						showReport();
					}
				}
			});
		}
		return jTable;
	}

	private void showReport() {
		// String input = JOptionPane.showInputDialog(StockBarcode.this,
		// "จำนวนหน้า", 1);
		// if (input != null) {
		// int pages = Integer.parseInt(input);
		String report = "report/barcode01.jasper";

		int row = jTable.getSelectedRow();
		params.put("PartIdent", jTable.getValueAt(row, 1).toString());
		params.put("Description", jTable.getValueAt(row, 2).toString());
		String newIdent = null;
		if (jTable.getValueAt(row, 5) != null) {
			newIdent = jTable.getValueAt(row, 5).toString();
		}
		if (newIdent == null || newIdent.equals("")) {
			newIdent = jTable.getValueAt(row, 1).toString();
			newIdent = newIdent.replace("-", "");
		}
		params.put("NewIdent", newIdent);
		// String s = String.format(" %,.00f / %s", Float.parseFloat(jTable
		// .getValueAt(row, 3).toString()), jTable.getValueAt(row, 4)
		// .toString());
		params.put("rowcount", new Integer(rowcount.getSelectedItem()
				.toString()));
		ReportDriver.runReport(params, report, 1);
		// }

	}

	/**
	 * This method initializes jPanel
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJPanel() {
		if (jPanel == null) {
			count = new JLabel();
			count.setBounds(new Rectangle(580, 7, 226, 27));
			count.setFont(new Font("Dialog", Font.PLAIN, 18));
			count.setText("จำนวน");
			jLabel2 = new JLabel();
			jLabel2.setBounds(new Rectangle(230, 10, 100, 22));
			jLabel2.setText("ชื่อสินค้า :");
			jLabel3 = new JLabel();
			jLabel3.setBounds(new Rectangle(20, 10, 100, 22));
			jLabel3.setText("รหัส :");
			rowcount = new JComboBox(new String[] { "10", "9", "8", "7", "6",
					"5", "4", "3", "2", "1" });
			rowcount.setEditable(false);
			rowcount.setBounds(new Rectangle(720, 10, 50, 22));
			rowcount.setToolTipText("จำนวนบรรทัด พิมพ์บาร์โค๊ด");

			jPanel = new JPanel();
			jPanel.setLayout(null);
			jPanel.setBackground(Color.ORANGE);
			jPanel.setPreferredSize(new Dimension(100, 40));

			jPanel.add(jLabel2, null);
			jPanel.add(jLabel3, null);
			jPanel.add(getDescript(), null);
			jPanel.add(getCode(), null);
			jPanel.add(count, null);
			jPanel.add(rowcount, null);

		}
		return jPanel;
	}

	/**
	 * This method initializes jTextField1
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getDescript() {
		if (descript == null) {
			descript = new JTextField();
			descript.setToolTipText("ป้อนชื่อสินค้า (ไม่จำเป็นต้องใส่ %)");
			descript.setFont(FONT1);
			descript.setBounds(new Rectangle(300, 8, 255, 26));
			descript.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					descript.selectAll();
					query();
					jTable.requestFocus();
					// String text = descript.getText();
					// if (text.length() == 0) {
					// sorter.setRowFilter(null);
					// } else {
					// try {
					// sorter.setRowFilter(RowFilter.regexFilter(text));
					// } catch (PatternSyntaxException pse) {
					// System.err.println("Bad regex pattern");
					// }
					// }
					// countData();
				}
			});
		}
		return descript;
	}

	private JTextField getCode() {
		if (code == null) {
			code = new JTextField();
			code.setToolTipText("ป้อนรหัสสินค้า (ไม่จำเป็นต้องใส่ %)");
			code.setBounds(new Rectangle(60, 8, 150, 26));
			code.setFont(FONT1);
			code.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					code.selectAll();
					query();
					jTable.requestFocus();
					// if (text.length() == 0) {
					// sorter.setRowFilter(null);
					// } else {
					// try {
					// sorter.setRowFilter(RowFilter.regexFilter(text));
					// } catch (PatternSyntaxException pse) {
					// System.err.println("Bad regex pattern");
					// }
					// }
					// countData();
				}
			});
		}
		return code;
	}

	private void countData() {
		count.setText(String.format("%,d", jTable.getRowCount()) + " รายการ");
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				StockBarcode thisClass = new StockBarcode();
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				thisClass.setVisible(true);
			}
		});
	}

	private void query() {
		ResultSet rs = null;
		String co = null;
		if (code.getText().equals(""))
			co = "%";
		else
			co = "%" + code.getText() + "%";
		String desc = null;
		if (descript.getText().equals(""))
			desc = "%";
		else
			desc = "%" + descript.getText().toLowerCase() + "%";
		try {
			pstmt.setString(1, co);
			pstmt.setString(2, desc);
			rs = pstmt.executeQuery();
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(this, e.getMessage());
			e.printStackTrace();
		}
		tm = new DBTableModel(rs, false, false);
		jTable.setModel(tm);

		jTable.getColumnModel().getColumn(3).setCellRenderer(MY_RENDERER);
		// sorter = new TableRowSorter<TableModel>(tm);
		// jTable.setRowSorter(sorter);
		countData();
	}

	private void initData() {
		try {
			db = new Database(new com.hxtt.sql.paradox.ParadoxDriver(),
					"jdbc:paradox:/." + "?charSet=MS874", null, null);
		} catch (SQLException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(this, e.getMessage());
		}
		db.createSQL(
				"Stock Query",
				"select PartIdent as 'รหัสสินค้า', Description as 'ชื่อสินค้า', ListPrice as 'ราคา', Unit as 'หน่วย', NewIdent as 'รหัสบาร์โค้ด' "
						+ "from stkbody where "
						+ "PartIdent like ? and lower(Description) like ?");
		pstmt = db.getStatement("Stock Query");

		jTable.setWidths(new int[] { 50, 150, 380, 100, 50, 120 });
	}

	/**
	 * This is the default constructor
	 */
	public StockBarcode() {
		super();
		initialize();
		initData();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(800, 600);
		this.setContentPane(getJContentPane());
		this.setTitle("Stock Barcode");
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.setFont(new Font("Dialog", Font.PLAIN, 14));
			jContentPane.add(getJScrollPane(), BorderLayout.CENTER);
			jContentPane.add(getJPanel(), BorderLayout.NORTH);
		}
		return jContentPane;
	}

} // @jve:decl-index=0:visual-constraint="10,10"
